<template>
  <ul class="city-alphabet">
    <li v-for="item in letters" :key="item" :ref="item"
      @click="handleLetterClick"
      @touchstart="handleTouchstart"
      @touchmove="handleTouchmove"
      @touchend="handleTouchend"
    >{{ item }}</li>
  </ul>
</template>

<script>
export default {
  name: 'city-alphabet',
  props: {
    cities: Object
  },
  data() {
    return {
      touching: false,
      startY: 0,
      timer: null
    }
  },
  computed: {
    letters() {
      let letters = [], i;

      for(i in this.cities) {
        letters.push(i);
      }

      return letters;
    }
  },
  updated() {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleLetterClick(e) {
      this.$emit('change', e.target.innerText);
    },
    handleTouchstart() {
      this.touching = true;
    },
    handleTouchmove(e) {
      if(this.touching) {
        if(this.timer) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
          let touchY = e.touches[0].clientY - 79,
              index = Math.floor((touchY - this.startY) / 20);
          
          if(index >= 0 && index <= this.letters.length) {
            this.$emit('change', this.letters[index]);
          }
        }, 16);
      }
    },
    handleTouchend() {
      this.touching = false;
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/variable.styl';

.city-alphabet
  position absolute
  top 1.58rem
  right 0
  bottom 0
  width .4rem
  display flex
  flex-direction column
  justify-content center
  align-items center
  li 
    line-height .4rem
    color $bgColor
</style>